import type { FC, Key } from 'react';
import { memo, useMemo } from 'react';
import { Group, Rect } from 'react-konva';
import CenterText from '../CenterText';
import { createChars } from './utils';
import { getSeat } from '../helper';

const padding: number = 4;

type SeatProps = {
  seatSize: number;
  seatJson: string;
}

const Seat: FC<SeatProps> = (props) => {
  const { seatSize } = props;

  const {
    row,
    price,
    column,
    seatNumber,
  } = getSeat(props.seatJson);

  const size = seatSize - padding * 2;

  const text = useMemo(() => {
    if (!seatNumber) return;
    const column = seatNumber.column;
    let number: Key = column.number;
    if (column.type === 'letter') {
      number = createChars(number - 1);
    }
    return `${number}`;
  }, [seatNumber]);

  const color = price?.priceLevelColor || '#1dcb54';

  return (
    <Group
      y={(row - 1) * seatSize}
      x={(column - 1) * seatSize}
    >
      <Rect
        fill={color}
        width={size}
        height={size}
        x={padding}
        y={padding}
        cornerRadius={4}
      />
      {!!text && (
        <CenterText
          fill='#fff'
          fontSize={12}
          size={seatSize}
          text={text}
        />
      )}
    </Group>
  );
}

export default memo(Seat);